package com.eutray.biz;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author ：chenxf
 * @date ：Created in 2019/10/11 16:49
 * @description：任务类
 * @modified By：
 * @version: $
 */
@Slf4j
@Service
public class MissionBiz {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String getMission(String id) throws Exception{
        long start = System.currentTimeMillis();
        log.debug("mission start 0/24");
        String data=redisTemplate.opsForValue().get(id);
        if(data==null){
            return awaitMission(id,start,1);
        }
        redisTemplate.delete(id);
        return data;
    }

    /**
     * 等待任务
     * @param id
     * @param start
     * @param times
     * @return
     */
    private String awaitMission(String id,long start,int times) throws Exception{
            if(start + 1000 * times - System.currentTimeMillis()>0) {
                Thread.sleep(start + 1000 * times - System.currentTimeMillis());
            }
            if(times==24){
                return  "OK";
            }
            log.debug("mission start {}/24",times);
            String data=redisTemplate.opsForValue().get(id);
            if(data==null){
                return awaitMission(id,start,++times);
            }
            redisTemplate.delete(id);
            return data;

    }
}
